package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.ContractFileLogic;
import cn.topevery.garden.dal.logic.ContractLogic;
import cn.topevery.garden.dal.logic.SectionLogic;
import cn.topevery.garden.entity.impot.ContractImportParam;
import cn.topevery.garden.entity.po.Contract;
import cn.topevery.garden.entity.po.ContractFile;
import cn.topevery.garden.entity.query.ContractQuery;
import cn.topevery.garden.entity.vo.ContractVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import cn.topevery.garden.wapi.utils.StatusUtils;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  合同管理
 *
 * @author code-generate
 * @date 2021-08-06
 */
@Api(tags = "合同管理接口")
@RestController
@RequestMapping("/contract")
public class ContractController extends BaseController {


    @Autowired
    ContractLogic contractLogic;

    @Autowired
    SectionLogic sectionLogic;

    @Autowired
    ContractFileLogic contractFileLogic;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<Contract>> listPage(@RequestBody ContractQuery query) {
        DataPager<Contract> page = contractLogic.listPage(query);
        for(Contract contract: page.records){
            List<ContractFile> list = contractFileLogic.getListByPid(contract.getId());
            contract.setFileList(list);
        }
        return JsonResult.ok(page);
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(@Valid @RequestBody Contract dto) {
        if(dto.getId() == null){
            dto.setDbStatus(false);
        }
        Integer UserId=getUser().id;
        boolean isSave = contractLogic.saveOrUpdate(UserId.toString(),dto);
        if(isSave) {
            // 保存附件
            contractFileLogic.saveOrUpdate(UserId.toString(), dto.getId(), dto.getFileList());

            return JsonResult.ok(true);
        }else {
            return JsonResult.error("保存失败");
        }
    }



    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        contractLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(ContractQuery query, HttpServletResponse response) {
        List<Contract> list = contractLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", Contract.class, "", response);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<ContractVO> persons = null;
        try {
            persons = ExcelUtils.importExcel(file, 0, 1, ContractVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<ContractVO> newData = new ArrayList<>();
        for (ContractVO p : persons) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getName() == null) {
                break;
            }
            boolean isExists1 = contractLogic.isExit("c_name", p.getName());
            if (isExists1) {
                anaylsisRes += "合同名称与现有重复；";
            }
            boolean isExists2 = contractLogic.isExit("c_contract_code", p.getContractCode());
            if (isExists2) {
                anaylsisRes += "合同编码与现有重复；";
            }

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody ContractImportParam param) {

        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (ContractVO p : param.getTableData()) {
                Contract tmp = new Contract();

                tmp.setName(p.getName());
                tmp.setContractCode(p.getContractCode());
                tmp.setBiddingDate(p.getBiddingDate());
                tmp.setBiddingMoney(p.getBiddingMoney());
                tmp.setServiceStartDate(p.getServiceStartDate());
                tmp.setServiceEndDate(p.getServiceEndDate());
                tmp.setCompanyPersonA(p.getCompanyPersonA());
                tmp.setCompanyPersonAPhone(p.getCompanyPersonAPhone());
                tmp.setCompanyPersonB(p.getCompanyPersonB());
                tmp.setCompanyPersonBPhone(p.getCompanyPersonBPhone());
                tmp.setManagerPerson(p.getManagerPerson());
                tmp.setManagerPersonPhone(p.getManagerPersonPhone());
                tmp.setState(StatusUtils.getStatus(p.getState()));
                tmp.setStateDesc(p.getStateDesc());
                tmp.setIsTimeout(StatusUtils.getIsTime(p.getIsTimeout()));
                tmp.setSectionId(sectionLogic.getSectionIdByName(p.getSection()));
                tmp.setRemark(p.getRemark());

                contractLogic.saveOrUpdate(user.id.toString(),tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }


}
